<script>
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import CargoCascader from '@comp/warehouse/CargoCascader.vue'
import $file from '@/libs/globalFunction/file'
import dayjs from 'dayjs'
import { getAction } from '@api/manage'
import utils from '@/utils/utils'

export default {
  name: 'OutboundRecordPickingForm',
  components: { CargoCascader },
  mixins: [JVxeTableModelMixin],
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      confirmLoading: false,
      url: {
        edit: '/wms/outbound/outbound-record/pick',
        outboundRecordItem: {
          list: '/wms/outbound/outbound-record/queryOutboundRecordItemByMainId'
        },
        outboundRecordFile: {
          list: '/wms/outbound/outbound-record/queryOutboundRecordFileByMainId'
        },
        outboundRecordCargoMember: {
          list: '/wms/outbound/outbound-record/queryOutboundRecordCargoMemberByMainId'
        },
        outboundVehicleInspectionInfo: {
          list: '/wms/outbound/outbound-record/queryOutboundVehicleInspectionInfoByMainId'
        },
        outboundVehicleInspectionRecord: {
          list: '/wms/outbound/outbound-record/queryOutboundVehicleInspectionRecordByMainId'
        },
        outboundVehicleInspectionRecordItem: {
          list: '/wms/outbound/vehicle-check-item/list'
        }
      },
      outboundRecordItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            width: '110px'
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            minWidth: '180px'
          },
          {
            title: '单位',
            key: 'unit_dictText',
            type: JVXETypes.normal,
            dictCode: 'ji_unit',
            width: '60px'
          },
          {
            title: '库存数量',
            key: 'quantity',
            type: JVXETypes.normal,
            width: '80px'
          },
          {
            title: '辅单位',
            key: 'secondaryUnit_dictText',
            type: JVXETypes.normal,
            dictCode: 'zl_unit',
            width: '70px'
          },
          {
            title: '辅数量',
            key: 'secondaryQuantity',
            type: JVXETypes.normal,
            width: '80px'
          },
          {
            title: '生产日期',
            key: 'productionDate',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '限用日期',
            key: 'expirationDate',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '批次号',
            key: 'batchNumber',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '物料批号',
            key: 'materialBatchNumber',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '储位',
            key: 'storageLocation_dictText',
            type: JVXETypes.normal,
            width: '130px'
          },
          {
            title: '质检状态',
            key: 'qualityInspectionStatus_dictText',
            type: JVXETypes.normal,
            width: '80px'
          },
          {
            title: '通知出库数量',
            key: 'notifyOutboundQuantity',
            type: JVXETypes.normal,
            width: '120px'
          },
          {
            title: '拣料数量',
            key: 'pickingQuantity',
            type: JVXETypes.inputNumber,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              // { 
              //   validator: (rule, value, callback, source, options) => {
              //     const row = source // 当前行数据
              //     if (value && row.notifyOutboundQuantity && value > row.notifyOutboundQuantity) {
              //       callback('拣料数量不能大于通知出库数量')
              //     } else {
              //       callback()
              //     }
              //   },
              //   message: '拣料数量不能大于通知出库数量'
              // }
            ]
          }
        ]
      },
      cargoGroupMemberTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '姓名',
            key: 'memberName',
            type: JVXETypes.normal,
            width: '110px'
          },
          {
            title: '作业工种',
            key: 'jobType_dictText',
            type: JVXETypes.normal,
            minWidth: '180px'
          },
          {
            title: '作业吨数',
            key: 'jobWeight',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          }
        ]
      },
      outboundRecordFileTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '附件名称',
            key: 'fileName',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: ''
          },
          {
            title: '文件大小',
            key: 'fileSizeFormat',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action'
          }
        ]
      },
      outboundVehicleInspectionRecordTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '项目',
            key: 'itemName',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '位置',
            key: 'position',
            type: JVXETypes.normal,
            align: 'center',
            width: '130px'
          },
          {
            title: '合格标准',
            key: 'standard',
            type: JVXETypes.normal,
            width: '280px'
          },
          {
            title: '检查方法',
            key: 'inspectionMethod',
            type: JVXETypes.normal,
            width: '280px'
          },
          {
            title: '问题描述',
            key: 'problemDesc',
            type: JVXETypes.textarea,
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '处理意见',
            key: 'handlingOpinion',
            type: JVXETypes.textarea,
            placeholder: '请输入${title}',
            defaultValue: ''
          }
        ]
      },
      outboundVehicleInspectionInfo: {
        vehicleNumber: null,
        transporter: null,
        pickUpDate: dayjs().format('YYYY-MM-DD')
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  methods: {
    picking(record) {
      if (!record) {
        return
      }
      this.model = Object.assign({}, record)
      this.fetchItemData()
    },
    fetchItemData() {
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.outboundRecordItem.list, params, this.outboundRecordItemTable, (res) => {
          if (this.outboundRecordItemTable.dataSource && this.outboundRecordItemTable.dataSource.length > 0) {
            this.$set(this.model, 'pickerRemark', this.outboundRecordItemTable.dataSource[0].pickerRemark)
            this.outboundRecordItemTable.dataSource.forEach((item) =>{
              item.pickingQuantity = item.notifyOutboundQuantity
            })
          }
        })
        this.requestSubTableData(this.url.outboundRecordCargoMember.list, params, this.cargoGroupMemberTable)
        this.fetchVehicleInspectionInfoData(params)
        if (this.model.pickingStatus === '1') {
          this.requestSubTableData(this.url.outboundVehicleInspectionRecordItem.list, params, this.outboundVehicleInspectionRecordTable)
        } else if (['2', '3'].includes(this.model.pickingStatus)) {
          this.requestSubTableData(this.url.outboundVehicleInspectionRecord.list, params, this.outboundVehicleInspectionRecordTable)
        }
      }
    },
    fetchVehicleInspectionInfoData(params) {
      getAction(this.url.outboundVehicleInspectionInfo.list, params).then((res) => {
        let { result } = res
        if (result && result.length) {
          this.outboundVehicleInspectionInfo = result[0]
        }
      })
    },
    cargoSelectChange({ value, list }) {
      if (list.length > 0) {
        this.cargoGroupMemberTable.dataSource = list.map(item => {
          return {
            memberName: item.memberName,
            jobType: item.jobType,
            jobType_dictText: item.jobType_dictText,
            memberId: item.id,
            groupId: item.groupId,
            teamId: value[0]
          }
        })
      }
    },
    handleFileChange(fileList) {
      if (!fileList || fileList.length <= 0) {
        return
      }
      fileList.forEach(item => {
        item.fileSizeFormat = $file.calculateFileSize(item.fileSize)
      })
      this.outboundRecordFileTable.dataSource = fileList
    },
    handleCargoDelete({ deleteRows }) {
      this.cargoGroupMemberTable.dataSource = this.cargoGroupMemberTable.dataSource.filter(row =>
        !deleteRows.some(item => item.id === row.id)
      )
    },
    async handleSubmit() {
      const errMap = await this.$refs.outboundRecordItem.validateTable()
      if (errMap) {
        return
      }
      // if (!this.cargoGroupMemberTable.dataSource.length) {
      //   this.$message.error('请选择作业人员')
      //   return
      // }
      const errMap2 = await this.$refs.cargoGroupMember.validateTable()
      if (errMap2) {
        return
      }
      // let count = 0;
      // if(this.outboundRecordItemTable.dataSource?.length > 0){
      //   this.outboundRecordItemTable.dataSource.forEach((item) => {
      //     if(utils.sub(item.notifyOutboundQuantity, item.pickingQuantity) < 0){
      //       count = count + 1;
      //       this.validateError(item.materialName + ': 拣料数量大于通知出库数量')
      //     }
      //   })
      // }
      // if(count > 0){
      //   return
      // }
      const formData = {
        id: this.model.id,
        outboundRecordItemList: this.outboundRecordItemTable.dataSource
          .filter(item => item.pickingQuantity)
          .map(item => {
            return {
              id: item.id,
              pickingQuantity: item.pickingQuantity,
              pickerRemark: this.model.pickerRemark
            }
          }),
        outboundRecordFileList: this.outboundRecordFileTable.dataSource,
        outboundRecordCargoMemberList: this.cargoGroupMemberTable.dataSource.map(item => {
          return {
            ...item,
            cargoType: 3,
            id: null
          }
        }),
        outboundVehicleInspectionInfo: this.outboundVehicleInspectionInfo,
        outboundVehicleInspectionRecordList: this.outboundVehicleInspectionRecordTable.dataSource.map(item => {
          return {
            ...item,
            id: null
          }
        })
      }
      this.request(formData)
    },
    rowspanMethod({ row, column, rowIndex, columnIndex }) {
      const visibleData = this.outboundVehicleInspectionRecordTable.dataSource
      const cellValue = row[column.property]
      if (column.property === 'itemName' && cellValue) {
        const prevRow = visibleData[rowIndex - 1]
        let nextRow = visibleData[rowIndex + 1]
        if (prevRow && prevRow.itemName === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow.itemName === cellValue) {
            nextRow = visibleData[++countRowspan + rowIndex]
          }
          return { rowspan: countRowspan, colspan: 1 }
        }
      }
      if (column.property === 'position' && cellValue) {
        const prevRow = visibleData[rowIndex - 1]
        let nextRow = visibleData[rowIndex + 1]
        if (prevRow && prevRow.itemName === row.itemName && prevRow.position === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (
            nextRow &&
            nextRow.itemName === row.itemName &&
            nextRow.position === cellValue
            ) {
            nextRow = visibleData[++countRowspan + rowIndex]
          }
          return { rowspan: countRowspan, colspan: 1 }
        }
      }
    }
  }
}
</script>

<template>
  <a-spin :spinning="confirmLoading">
    <div class="ant-descriptions-title">出库明细</div>
    <j-vxe-table
      keep-source
      ref="outboundRecordItem"
      :loading="outboundRecordItemTable.loading"
      :columns="outboundRecordItemTable.columns"
      :dataSource="outboundRecordItemTable.dataSource"
      :maxHeight="300"
      :rowNumber="true"
      :rowSelection="false"
      :toolbar="false"
    />
    <j-upload
      style="margin: 10px 0"
      :returnUrl="false"
      @change="handleFileChange" />
    <a-input v-model="model.pickerRemark" placeholder="请输入备注" />
    <div style="margin-bottom: 10px"></div>
    <div class="ant-descriptions-title">作业信息</div>
    <cargo-cascader
      style="margin-bottom: 10px"
      :max-level="2"
      load-children-on-select
      @change="cargoSelectChange" />
    <j-vxe-table
      keep-source
      ref="cargoGroupMember"
      :loading="cargoGroupMemberTable.loading"
      :columns="cargoGroupMemberTable.columns"
      :dataSource="cargoGroupMemberTable.dataSource"
      :maxHeight="300"
      :rowNumber="true"
      :rowSelection="true"
      :toolbar="true"
      :toolbarConfig="{
            slots: ['prefix', 'suffix'],
            btn: ['remove', 'clearSelection'],
          }"
      @remove="handleCargoDelete"
    />
    <div style="margin-top: 10px" class="ant-descriptions-title">车辆检查项目</div>
    <a-form-model ref="form" :model="outboundVehicleInspectionInfo">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="车牌号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="vehicleNumber">
            <a-input v-model="outboundVehicleInspectionInfo.vehicleNumber" placeholder="请输入车牌号"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="运输商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="transporter">
            <a-input v-model="outboundVehicleInspectionInfo.transporter" placeholder="请输入运输商"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="提货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickUpDate">
            <j-date
              style="width: 100%"
              :show-time="true"
              date-format="YYYY-MM-DD"
              placeholder="请输入提货日期"
              class="query-group-cust"
              v-model="outboundVehicleInspectionInfo.pickUpDate" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <j-vxe-table
      keep-source
      ref="outboundVehicleInspectionRecord"
      :loading="outboundVehicleInspectionRecordTable.loading"
      :columns="outboundVehicleInspectionRecordTable.columns"
      :dataSource="outboundVehicleInspectionRecordTable.dataSource"
      :maxHeight="500"
      :rowNumber="false"
      :rowSelection="false"
      :toolbar="false"
      :span-method="rowspanMethod"
    />
  </a-spin>
</template>

<style scoped>

</style>